package com.itheima.controller.store;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.store.Company;
import com.itheima.service.store.CompanyService;
import com.itheima.service.store.impl.CompanyServiceImpl;
import com.itheima.utils.BeanUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/store/company/*")
public class CompanyServlet extends BaseServlet {

    //根据页码获取企业列表
    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取分页属性
        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");
        //System.out.println(pageNum);
        //获取列表
        Page<Company> page = companyService.findAll(pageNum, pageSize);
        //配置分页信息
        PageInfo<Company> pageinfo = new PageInfo<>(page);
        //存入请求域
        req.setAttribute("page",pageinfo);
        //跳转页面
        req.getRequestDispatcher("/pages/store/company/list.jsp").forward(req,resp);
    }
    //保存企业信息
    private void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //封装用户信息
        Company company = BeanUtil.fillBean(req, Company.class, "yyyy-mm-dd");
        //添加用户
        companyService.addCompany(company);
        //刷新页面
        list(req,resp);
    }

    //删除多条记录
    private void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String ids = req.getParameter("ids");
        //System.out.println(ids);
        //删除
        boolean isDel = companyService.deleteByIds(ids);
        //System.out.println("============="+isDel);
        //响应
        resp.getWriter().write(mapper.writeValueAsString(isDel));
        //刷新页面
        //list(req,resp);
    }

    //通过id找到企业信息
    private void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        //添加用户
        Company company = companyService.findById(id);
        //设置到请求域
        req.setAttribute("company",company);
        //跳转到编辑页面
        req.getRequestDispatcher("/pages/store/company/update.jsp").forward(req,resp);
    }


    //通过id修改
    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //封装用户信息
        Company company = BeanUtil.fillBean(req, Company.class, "yyyy-mm-dd");
        //更新信息
        companyService.updateCompany(company);
        //刷新页面
        list(req,resp);
    }
}
